import os
import hashlib
import shutil
import argparse

def hash_file(file_path):
    """计算文件的SHA-256哈希值"""
    hasher = hashlib.sha256()
    with open(file_path, 'rb') as f:
        buf = f.read(65536)  # 每次读取64KB
        while buf:
            hasher.update(buf)
            buf = f.read(65536)
    return hasher.hexdigest()

def find_duplicates(directory):
    """查找目录中的重复文件"""
    hashes = {}
    duplicates = []
    
    for root, _, files in os.walk(directory):
        for filename in files:
            file_path = os.path.join(root, filename)
            file_hash = hash_file(file_path)
            if file_hash in hashes:
                duplicates.append(file_path)
                if hashes[file_hash] not in duplicates:
                    duplicates.append(hashes[file_hash])
            else:
                hashes[file_hash] = file_path
    
    return duplicates

def move_to_bak(duplicates, bak_directory):
    """将重复文件移动到bak目录，保留一个副本"""
    if not os.path.exists(bak_directory):
        os.makedirs(bak_directory)
    seen_hashes = set()
    for file_path in duplicates:
        file_hash = hash_file(file_path)
        if file_hash not in seen_hashes:
            seen_hashes.add(file_hash)
            continue  # 跳过第一个出现的重复文件
        try:
            shutil.move(file_path, os.path.join(bak_directory, os.path.basename(file_path)))
            print(f"已移动文件: {file_path} 到 {bak_directory}")
        except Exception as e:
            print(f"移动文件 {file_path} 时出错: {e}")

if __name__ == "__main__":
    print("重复文件查找工具")
    print("-" * 20)
    
    # 获取目录路径
    while True:
        folder_path = input("请输入要检查的文件夹路径：").strip()
        if os.path.isdir(folder_path):
            break
        print("错误：请输入有效的文件夹路径")
    
    # 询问是否移动重复文件
    move_to_bak_flag = input("是否将重复文件移动到bak目录？(y/n): ").strip().lower() == 'y'

    duplicate_files = find_duplicates(folder_path)
    if duplicate_files:
        print("\n发现重复文件:")
        for file in duplicate_files:
            print(file)
        if move_to_bak_flag:
            bak_directory = os.path.join(folder_path, "bak")
            move_to_bak(duplicate_files, bak_directory)
    else:
        print("没有发现重复文件。")